package com.example.spider.provider.m3u8.dto;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.experimental.Accessors;
import org.shoulder.crypto.symmetric.SymmetricAlgorithmEnum;
import org.shoulder.crypto.symmetric.impl.DefaultSymmetricCipher;

@Getter
@Setter
@Accessors(chain = true)
public class M3u8Key {

    private volatile boolean init = false;

    private String uri;

    private String url;

    /**
     * AES-128
     */
    private String method;

    private String ivStr;

    private boolean encrypted = false;

    private byte[] key;

    //if (iv.startsWith("0x"))
    //            ivByte = StrUtil.hexStringToByteArray(iv.substring(2));
    private byte[] iv = new byte[16];

    public static M3u8Key newNonEncryptKey() {
        M3u8Key k = new M3u8Key();
        k.setEncrypted(false);
        return k;
    }

    public boolean isEncrypted() {
        return method != null && !"NONE".equals(method);
    }

    @SneakyThrows
    public byte[] decrypt(byte[] input) {
        if (!isEncrypted()) {
            return input;
        }

        return DefaultSymmetricCipher.getFlyweight(SymmetricAlgorithmEnum.AES_CBC_PKCS5Padding.getAlgorithmName())
                .decrypt(key, iv, input);
    }
}
